package model

import (
	"global/structs"
	"github.com/ngaut/log"
	"time"
	"fmt"
)

type orderCoinModel struct {}

var OrderCoinModel = new(orderCoinModel)

// 获取指定数量的订单数据
func (orderCoinModel) GetOrderCoins(lastId int) []structs.OrderCoin {
	orders := make([]structs.OrderCoin, 0)
	err := MainDB.Where("id>?", lastId).Asc("id").Find(&orders)
	if err != nil {
		log.Errorf("get last %d order coins error, msg: %s", lastId, err.Error())
		return nil
	}
	return orders
}

// 获取总记录数
func (orderCoinModel) GetCount() int {
	order := new(structs.OrderCoin)
	c, err := MainDB.Count(order)
	if err != nil {
		log.Errorf("get order coin count error, msg: %s", err.Error())
		return 0
	}
	return int(c)
}

func (orderCoinModel) GetMinMaxSum(from, to string) map[string][]byte {
	start := int(time.Now().Unix() - 86400)
	sql := fmt.Sprintf("SELECT max(price) max, min(price) min, sum(number) s FROM `order_coin` WHERE coin_from='%s' and coin_to='%s' and create_time > %d", from, to, start)
	log.Debugf("get min|max|sum sql: %s", sql)
	res, err := MainDB.Query(sql)
	if err != nil || len(res) == 0 {
		log.Errorf("query min, max, sum error, msg: %v", err)
		return nil
	}
	return res[0]
}

func (orderCoinModel) Get24HoursNumAndMoney(from, to string, start int) map[string][]byte {
	sql := fmt.Sprintf("SELECT SUM(number) AS num, SUM(price * number) AS money FROM `order_coin` WHERE coin_from='%s' AND coin_to='%s' AND create_time >= %d", from, to, start)
	res, err := MainDB.Query(sql)
	if err != nil || len(res) == 0 {
		log.Errorf("query 24 hours number and money error, msg: %s", err.Error())
		return nil
	}
	return res[0]
}

func (orderCoinModel) GetFirstOrder(from, to string) *structs.OrderCoin {
	item := new(structs.OrderCoin)
	_, err := MainDB.Where("coin_from=?", from).Where("coin_to=?", to).Asc("id").Get(item)
	if err != nil {
		log.Errorf("get first order error, msg: %s", err.Error())
		return nil
	}
	return item
}

func (orderCoinModel) Get24UpAndDown(from, to string, start int) *structs.OrderCoin {
	item := new(structs.OrderCoin)
	_, err := MainDB.Where("coin_from=?", from).Where("coin_to=?", to).Where("create_time<=?",start).Desc("id").Get(item)
	if err != nil {
		log.Errorf("get 24 hours ups and downs error, msg: %s", err.Error())
		return nil
	}
	return item
}